package com.aisino.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author guochuantao
 * @version 1.0
 * @description
 * @since 2024/8/14 下午3:28
 */

public class ThreadPerformanceComparison {

    private static final int TASK_COUNT = 100; // 定义任务数量

    // 定义一个简单的任务，执行一些计算
    private static class SimpleTask implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 1000000; i++) {
                //计算i的平方根
                Math.sqrt(i);
            }
        }
    }

    // 单线程执行任务
    private static long executeSingleThreaded() {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < TASK_COUNT; i++) {
            new SimpleTask().run();
        }
        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }

    // 使用线程池多线程执行任务
    private static long executeMultiThreaded() throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        List<Future<?>> futures = new ArrayList<>();
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < TASK_COUNT; i++) {
            futures.add(executorService.submit(new SimpleTask()));
        }

        // 等待所有任务完成
        for (Future<?> future : futures) {
            future.get();
        }

        long endTime = System.currentTimeMillis();
        executorService.shutdown();
        return endTime - startTime;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        long singleThreadedTime = executeSingleThreaded();
        long multiThreadedTime = executeMultiThreaded();

        System.out.println("Single-threaded execution time: " + singleThreadedTime + " ms");
        System.out.println("Multi-threaded execution time: " + multiThreadedTime + " ms");

        // 计算效率提升比例
        double improvement = ((double) singleThreadedTime / multiThreadedTime) * 100;
        System.out.printf("Multi-threading improved performance by %.2f%%\n", improvement);
    }
}
